"""
核验服务
创建时间：2025-09-12
作者：开发团队
目的：处理二维码核验相关业务逻辑
"""

from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError
from datetime import datetime, timezone
from ..models.verification import VerificationRecord
from ..models.special_visitor import SpecialVisitor
from ..services.qr_service import decode_qr_data
from ..utils.logger import get_logger

# 获取日志记录器
logger = get_logger(__name__)


def verify_qr_code(db: Session, qr_data: str, guard_id: int) -> dict[str, object]:
    """
    验证二维码数据
    :param db: 数据库会话
    :param qr_data: 二维码数据
    :param guard_id: 门卫ID
    :return: 验证结果和访客信息
    """
    try:
        # 解码二维码数据
        decoded_data = decode_qr_data(qr_data)
        
        # 检查数据有效性
        if not decoded_data.get("visitor_name") or not decoded_data.get("visitor_phone"):
            raise ValueError("二维码数据不完整")
        
        # 检查是否过期
        expires_at = datetime.fromisoformat(str(decoded_data.get("expires_at", "")))
        if datetime.now(timezone.utc) > expires_at:
            return {
                "result": "expired",
                "message": "二维码已过期"
            }
        
        # 检查是否为特殊访客
        special_visitor = db.query(SpecialVisitor).filter(
            SpecialVisitor.phone == decoded_data["visitor_phone"]
        ).first()
        
        is_special = special_visitor is not None
        special_type = special_visitor.type if special_visitor else None
        
        # 构造访客信息
        visitor_info = {
            "name": decoded_data["visitor_name"],
            "phone": decoded_data["visitor_phone"],
            "id_card": decoded_data.get("visitor_id_card", ""),
            "company": decoded_data.get("visitor_company", ""),
            "visit_time": decoded_data["visit_time"],
            "purpose": decoded_data["purpose"],
            "host_name": decoded_data["host_name"],
            "host_phone": decoded_data["host_phone"],
            "expires_at": decoded_data["expires_at"],
            "is_special": is_special,
            "special_type": special_type
        }
        
        return {
            "result": "valid",
            "visitor_info": visitor_info
        }
    except ValueError as e:
        logger.error(f"二维码验证失败: {str(e)}")
        return {
            "result": "invalid",
            "message": str(e)
        }
    except Exception as e:
        logger.error(f"二维码验证异常: {str(e)}")
        return {
            "result": "invalid",
            "message": "二维码验证失败"
        }


def submit_verification_result(
    db: Session, 
    qr_data: str, 
    guard_id: int, 
    result: str, 
    notes: str | None = None
) -> int:
    """
    提交核验结果
    :param db: 数据库会话
    :param qr_data: 二维码数据
    :param guard_id: 门卫ID
    :param result: 核验结果
    :param notes: 备注信息
    :return: 记录ID
    """
    try:
        # 解码二维码数据
        decoded_data = decode_qr_data(qr_data)
        
        # 创建核验记录
        record = VerificationRecord(
            visitor_name=str(decoded_data["visitor_name"]),
            visitor_phone=str(decoded_data["visitor_phone"]),
            visitor_id_card=str(decoded_data.get("visitor_id_card", "")),
            visitor_company=str(decoded_data.get("visitor_company", "")),
            host_name=str(decoded_data["host_name"]),
            host_phone=str(decoded_data["host_phone"]),
            visit_time=datetime.fromisoformat(str(decoded_data["visit_time"])),
            purpose=str(decoded_data["purpose"]),
            verification_time=datetime.now(timezone.utc),
            guard_id=guard_id,
            result=result,
            notes=notes,
            qr_data=qr_data
        )
        
        # 保存到数据库
        db.add(record)
        db.commit()
        db.refresh(record)
        
        logger.info(f"核验记录创建成功: ID={record.id}")
        return getattr(record, 'id')
    except SQLAlchemyError as e:
        db.rollback()
        logger.error(f"保存核验记录失败: {str(e)}")
        raise ValueError("保存核验记录失败")
    except Exception as e:
        db.rollback()
        logger.error(f"提交核验结果异常: {str(e)}")
        raise ValueError("提交核验结果失败")


def get_verification_records(db: Session, skip: int, limit: int) -> tuple[list[VerificationRecord], int]:
    """
    获取核验记录列表
    :param db: 数据库会话
    :param skip: 跳过的记录数
    :param limit: 返回的记录数
    :return: (记录列表, 总数)
    """
    try:
        query = db.query(VerificationRecord)
        total = query.count()
        records = query.offset(skip).limit(limit).all()
        return records, total
    except SQLAlchemyError as e:
        logger.error(f"查询核验记录失败: {str(e)}")
        raise ValueError("查询核验记录失败")


def get_verification_record_by_id(db: Session, record_id: int) -> VerificationRecord | None:
    """
    根据ID获取核验记录详情
    :param db: 数据库会话
    :param record_id: 记录ID
    :return: 核验记录对象或None
    """
    try:
        return db.query(VerificationRecord).filter(VerificationRecord.id == record_id).first()
    except SQLAlchemyError as e:
        logger.error(f"查询核验记录详情失败: {str(e)}")
        return None